import { handleLoginFailure } from '@/utils'
import { isWeixin } from '@/utils/util'
import { VUE_APP_API_URL } from '@/config'
import cookie from '@/utils/cookie'
import { replace } from '@/utils/router'

const defaultOpt = { login: true }

function baseRequest(options) {
  const token = cookie.get('accessToken')
  options.header = {
    ...options.header,
    Authorization: 'Bearer ' + token,
    ...(options.headers || {})
  }

  const { url, params, data, login, ...option } = options

  return new Promise((resolve, reject) => {
    uni.request({
      url: VUE_APP_API_URL + url,
      method: option.method || 'GET',
      data: params || data,
      header: options.header,
      ...option,
      success: (res) => {
        const data = res.data || {}
        // #ifdef H5
        if (data.code == 1004004002) {
          if (isWeixin()) {
            const url = cookie.get('index_url')
            location.href = url
            return
          }
        }
        // #endif

        if (res.statusCode !== 200) {
          if (res.statusCode === 401 && data.code === 1000 && login !== false) {
            console.log('检测到登录凭证失效，跳转到登录页')
            uni.hideLoading()
            handleLoginFailure()
            uni.showToast({
              title: data.msg || data.message || '登录凭证失效',
              icon: 'none',
              duration: 2000,
            })
            reject({ msg: data.msg || data.message || '登录凭证失效', res, data, toLogin: true })
            return
          }

          reject({ msg: '请求失败', res, data })
          return
        }

        if (data.code == 401 && login !== false) {
          uni.hideLoading()
          handleLoginFailure()
          uni.showToast({
            title: data.msg,
            icon: 'none',
            duration: 2000,
          })
          reject({ msg: data.msg, res, data })
          return
        }

        if (data.code == 1000 && (data.message === '登录凭证失效' || data.msg === '登录凭证失效') && login !== false) {
          console.log('检测到登录凭证失效（响应体code: 1000），跳转到登录页')
          uni.hideLoading()
          handleLoginFailure()
          uni.showToast({
            title: data.msg || data.message,
            icon: 'none',
            duration: 2000,
          })
          reject({ msg: data.msg || data.message, res, data, toLogin: true })
          return
        }

        if (data.code != 0) {
          uni.showToast({
            title: data.msg,
            icon: 'none',
            duration: 2000,
          })
          reject({ data, res })
          return
        }

        resolve(data.data, res)
      },
      fail: (error) => {
        if (options.login !== false) {
          handleLoginFailure()
        }
        reject({ msg: '未登录', toLogin: true })
      }
    })
  })
}

const request = ['post', 'put', 'patch'].reduce((request, method) => {
  request[method] = (url, data = {}, options = {}) => {
    return baseRequest(Object.assign({ url, data, method: method.toUpperCase() }, defaultOpt, options))
  }
  return request
}, {})

  ;['get', 'delete', 'head'].forEach(method => {
    request[method] = (url, params = {}, options = {}) => {
      return baseRequest(Object.assign({ url, params, method: method.toUpperCase() }, defaultOpt, options))
    }
  })

/**
 * 支付宝小程序授权登录
 */
export function alipayAuthLogin(data) {
  return request.post('/member/auth/auth-alipay-miniapp-login', data, {
    login: false
  });
}

export default request
